<template>
  <page-header-wrapper>
    <a-card class="table-card">
      <GzSearchForm :searchFunc="searchFunc" :resetFunc="()=>{searchData = {}}">
        <a-form-item label="" class="table-search-item">
          <a-input v-model:value="searchData['channelCode']" placeholder="渠道编号" />
        </a-form-item>
        <a-form-item label="" class="table-search-item">
          <a-input v-model:value="searchData['channelName']" placeholder="渠道名称" />
        </a-form-item>
      </GzSearchForm>

      <!-- 列表渲染 -->
      <GzTable
        ref="infoTableRef"
        :init-data="true"
        :req-table-data-func="reqTableDataFunc"
        :table-columns="tableColumns"
        :search-data="searchData"
      >
        <template #topBtnSlot>
          <a-button v-if="$access('ENT_CHANNEL_SELF_ADD')" type="primary" @click="addOrEditFunc">
            <plus-outlined />新建渠道码
          </a-button>
          <!-- 导出渠道码信息 -->
          <a-button v-if="$access('ENT_CHANNEL_SELF_EXPT')" type="primary" @click="exportCodeMessage">
            <export-outlined />导出渠道码信息
          </a-button>
          <!-- 导出渠道码二维码图 -->
          <a-button v-if="$access('ENT_CHANNEL_SELF_EXPT')" type="primary" @click="exportCode">
            <export-outlined />导出二维码
          </a-button>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'isDistanceLimit'">
            <a-switch :checked="record.isDistanceLimit === 1 ? true : false" @change="changeStatus(record)" />
          </template>
          <template v-if="column.key == 'isDeleted'">
            <GzTableColState
              :state="record.isDeleted == 0 ? 1 : 0"
            />
          </template>
          <template v-if="column.key === 'operation'">
            <!-- 操作列插槽 -->
            <a-button v-if="$access('ENT_CHANNEL_SELF_EDIT')" type="link" @click="editFunc(record.activityChannelId)">编辑</a-button>
            <a-button v-if="$access('ENT_CHANNEL_SELF_EDIT') && record.isDeleted==0" type="link" @click="changeState(record.activityChannelId, 1)">停止</a-button>
            <a-button v-if="$access('ENT_CHANNEL_SELF_EDIT') && record.isDeleted==1" type="link" @click="changeState(record.activityChannelId, 0)">启用</a-button>
            <a-button v-if="$access('ENT_CHANNEL_SELF_VIEW')" type="link" @click="lookChnnelCode(record)">查看</a-button>
            <a-button v-if="$access('ENT_CHANNEL_SELF_EXPT')" type="link" @click="downloadOneCode(record)">下载</a-button>
          </template>
        </template>
      </GzTable>
    </a-card>
    <AddOrEdit ref="addOrEditRef" :callback-func="searchFunc" />
    <a-modal
      v-model:visible="open"
      :footer="null"
      :bodyStyle="{
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
      }"
    >
      <a-image :width="200" :src="codeUrl" />
      <div>{{ vdata.channelRecord.agentNo + '-' + vdata.channelRecord.channelCode }}</div>
      <div>{{ vdata.channelRecord.appId }}</div>
      <div>【 {{ useAgentStore().hostname }} 】</div>
    </a-modal>
    <!-- 是否开启距离限制 -->
    <a-modal
      :visible="vdata.stateVisible"
      okText="确定"
      cancelText="取消"
      style="padding: 32px 32px 24px"
      @cancel="() => vdata.stateVisible = false"
      @ok="distanceLimitHandle"
    >
      <template #title>
        <exclamation-circle-outlined style="color: #faad14; font-size: 22px; margin-right: 20px" />{{ vdata.title }}
      </template>
      <a-form
        v-show="vdata.isDistanceLimit == 0"
        ref="formRef"
        :model="vdata"
        layout="horizontal"
        :wrapperCol="{ span: 24 }"
      >
        <a-row>
          <a-col :span="24">
            <a-form-item label="距离限制（米）" name="username">
              <a-input-number v-model:value="vdata.distanceLimit" min="0" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <p v-if="vdata.isDistanceLimit == 1">请确认是否关闭？</p>
      <p v-if="vdata.isDistanceLimit == 0">请确认是否开启？</p>
    </a-modal>
  </page-header-wrapper>
</template>

<script setup lang="ts">
import { ref,reactive,getCurrentInstance } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import AddOrEdit from './AddOrEdit.vue'
import{$selfBuildList,$changeSelfBuild,$updateOneSelfBuild,$exportSelfBuildChannel,$exportSelfBuildChannelList}from '@/api/channel/index'
import { generateChannelCode, exportChannelCode } from '@/views/channel/channelUtils'
const { $infoBox, $access } =getCurrentInstance()!.appContext.config.globalProperties
import { useAgentStore } from '@/store/modules/agent'
const vdata: any = reactive({
  stateVisible: false,
  title: '确认关闭？',
  isDistanceLimit: 1,
  distanceLimit: '',
  channelRecord: null,  // 选择的渠道记录
})
const searchData = ref({
  channelType: '',
  channelCode: '',
  channelName: '',
}) as any
const tableColumns = ref([
  { title: '渠道码归属网点编号', dataIndex: 'agentNo', key: 'agentNo',width: 220, },
  { title: '渠道码归属网点名称', dataIndex: 'agentName', key: 'agentName' ,width: 200,},
  { title: '渠道码归属区县编号', dataIndex: 'agentNo3', key: 'agentNo3',width: 200,  },
  { title: '渠道码归属区县名称', dataIndex: 'agentName3', key: 'agentName3',width: 200,},
  { title: '渠道码编号', dataIndex: 'channelCode', key: 'channelCode',width: 250, },
  { title: '渠道码名称', dataIndex: 'channelName', key: 'channelName' ,width: 140, minWidth: 140, maxWidth: 250,},
  { title: '是否开启距离限制', dataIndex: 'isDistanceLimit', key: 'isDistanceLimit' ,width: 160, },
  { title: '距离限制', dataIndex: 'distanceLimit', key: 'distanceLimit',width: 140, minWidth: 140, maxWidth: 250, },
  { title: '渠道码地址', dataIndex: 'address', key: 'address',width: 200,  },
  { title: '经度', dataIndex: 'longitude', key: 'longitude',width: 140, minWidth: 140, maxWidth: 250,  },
  { title: '纬度', dataIndex: 'latitude', key: 'latitude' ,width: 140, minWidth: 140, maxWidth: 250, },
  { title: '创建时间', dataIndex: 'createdAt', key: 'createdAt',width: 200,   },
  { title: '最后修改时间', dataIndex: 'updateAt', key: 'updateAt' ,width: 200,  },
  { title: '状态', dataIndex: 'isDeleted', key: 'isDeleted', scopedSlots: { customRender: 'status' } ,width: 140, minWidth: 140, maxWidth: 250, },
   { key: 'operation', title: '操作', dataIndex: 'operation',width: 280, fixed: 'right', align: 'center' }
])
const total = ref()
const infoTableRef = ref()
const addOrEditRef = ref()
const open = ref(false)
const codeUrl = ref('')

/**
 * 请求自建渠道列表
 */
function reqTableDataFunc(params: any) {
  return new Promise((resolve, reject) => {
   $selfBuildList( {...searchData.value,...params,channelType:3})
      .then((res) => {
        total.value = res.total
        resolve(res)
      })
  })
}
const addOrEditFunc = () => {
  addOrEditRef.value.show()
}
const editFunc = (activityChannelId)=>{
   addOrEditRef.value.show(activityChannelId)
}

function searchFunc() {
  infoTableRef.value.refTable(true)
}
// 查看渠道码
const lookChnnelCode = async (record) => {  
  const url = await generateChannelCode(`${useAgentStore().channelBaseUrl}?channelId=${record.activityChannelId}&channelType=${record.channelType}`)
  codeUrl.value = url  
  vdata.channelRecord = record

  open.value = true
}
function changeState(activityChannelId,state){
  $changeSelfBuild({activityChannelId:activityChannelId,isDeleted:state}).then(res=>{
    $infoBox.message.success('修改成功')
       infoTableRef.value.refTable(true)
  })

}

// 是否开启距离限制
function changeStatus(record) {

  vdata.distanceLimit = null
  vdata.isDistanceLimit = record.isDistanceLimit
  vdata.stateVisible = true
  
  vdata.activityChannelId = record.activityChannelId
  if (record.isDistanceLimit == 0) {
    vdata.title = '确认开启?'
  } else {
    vdata.title = '确认关闭'
  }

}
function distanceLimitHandle() {
     let isDistanceLimit = 0
    let distanceLimit = '' as any
    if(vdata.isDistanceLimit == 1){
      isDistanceLimit = 0
      distanceLimit = ''
    }else{
      isDistanceLimit = 1
      distanceLimit = vdata.distanceLimit
      if (!distanceLimit || distanceLimit < 0) {
        $infoBox.message.error('请输入正确的距离限制')
        return
      }
    }
     $updateOneSelfBuild({ activityChannelId: vdata.activityChannelId, isDistanceLimit, distanceLimit })
    $infoBox.message.success('操作成功')
    infoTableRef.value.refTable()
    vdata.stateVisible = false
}
async function exportCode() {
  $infoBox.confirmDanger('确认导出？', '请确认是否导出渠道码？', async () => {
    //   // 获取活动渠道列表
    const channelList = await $exportSelfBuildChannel({ ...searchData.value})
    exportChannelCode(channelList,3)
  })
}
function exportCodeMessage(){
    $infoBox.confirmDanger('确认导出？', '请确认是否导出渠道码信息？', async () => {
     $exportSelfBuildChannelList({ ...searchData.value}).then(res=>{
      $infoBox.message.success('导出成功')
        const a = document.createElement('a')
        a.href = res
       a.download = '渠道码信息'
        document.body.appendChild(a)
       a.click()
       document.body.removeChild(a)
     })
  
  })
}
function downloadOneCode(record){
  $infoBox.confirmDanger('确认下载？', '请确认是否下载渠道码？', () => {
    //   // 获取活动渠道列表
  const  channelList = [record]
    exportChannelCode(channelList,3)
  })
}
</script>
<style>
</style>